<template>
  <div class="operation-log-container">
    <el-card class="log-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">操作日志管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport" :loading="exporting">
              导出日志
            </el-button>
            <el-button type="danger" @click="handleClear" :loading="clearing">
              清空日志
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索条件 -->
      <el-form :model="queryForm" :inline="true" class="search-form">
        <el-form-item label="操作用户">
          <el-input v-model="queryForm.username" placeholder="请输入操作用户" clearable />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="queryForm.operationType" placeholder="请选择操作类型" clearable>
            <el-option label="登录" value="LOGIN" />
            <el-option label="登出" value="LOGOUT" />
            <el-option label="新增" value="CREATE" />
            <el-option label="修改" value="UPDATE" />
            <el-option label="删除" value="DELETE" />
            <el-option label="查询" value="QUERY" />
            <el-option label="导出" value="EXPORT" />
            <el-option label="导入" value="IMPORT" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作模块">
          <el-select v-model="queryForm.module" placeholder="请选择操作模块" clearable>
            <el-option label="用户管理" value="USER" />
            <el-option label="角色管理" value="ROLE" />
            <el-option label="权限管理" value="PERMISSION" />
            <el-option label="区域管理" value="REGION" />
            <el-option label="物业管理" value="PROPERTY" />
            <el-option label="停车管理" value="PARKING" />
            <el-option label="安防管理" value="SECURITY" />
            <el-option label="系统配置" value="SYSTEM" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="queryForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 日志列表 -->
      <el-table
        :data="logList"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="操作用户" width="120" />
        <el-table-column prop="operationType" label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getOperationTypeTagType(row.operationType)">
              {{ getOperationTypeText(row.operationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="操作模块" width="120">
          <template #default="{ row }">
            <el-tag type="info">{{ getModuleText(row.module) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="操作描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="ipAddress" label="IP地址" width="120" />
        <el-table-column prop="userAgent" label="用户代理" width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="操作状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operationTime" label="操作时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.operationTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="操作日志详情"
      width="800px"
      :before-close="handleCloseDetail"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="操作用户">
          {{ currentLog.username }}
        </el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getOperationTypeTagType(currentLog.operationType)">
            {{ getOperationTypeText(currentLog.operationType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作模块">
          <el-tag type="info">{{ getModuleText(currentLog.module) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作状态">
          <el-tag :type="currentLog.status === 1 ? 'success' : 'danger'">
            {{ currentLog.status === 1 ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">
          {{ currentLog.ipAddress }}
        </el-descriptions-item>
        <el-descriptions-item label="操作时间">
          {{ formatDateTime(currentLog.operationTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="操作描述" :span="2">
          {{ currentLog.description }}
        </el-descriptions-item>
        <el-descriptions-item label="请求参数" :span="2">
          <pre class="log-detail-pre">{{ formatJson(currentLog.requestParams) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="响应结果" :span="2">
          <pre class="log-detail-pre">{{ formatJson(currentLog.responseResult) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="用户代理" :span="2">
          {{ currentLog.userAgent }}
        </el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2" v-if="currentLog.errorMessage">
          <pre class="log-detail-pre error-message">{{ currentLog.errorMessage }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { showMessage } from '@/utils/message'
import { getSystemLogList, type SystemLogQueryParams, type SystemLog } from '@/api/user'

// 作者：Wu.Liang
// 操作日志管理组件

interface OperationLog {
  id: number
  username: string
  operationType: string
  module: string
  description: string
  ipAddress: string
  userAgent: string
  status: number
  operationTime: string
  requestParams: string
  responseResult: string
  errorMessage: string
}

const queryForm = reactive({
  username: '',
  operationType: '',
  module: '',
  timeRange: []
})

const logList = ref<OperationLog[]>([])
const loading = ref(false)
const exporting = ref(false)
const clearing = ref(false)
const detailVisible = ref(false)
const currentLog = ref<OperationLog>({} as OperationLog)
const selectedLogs = ref<OperationLog[]>([])

const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 获取操作日志列表
const getOperationLogList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params: SystemLogQueryParams = {
      current: pagination.current,
      size: pagination.size,
      username: queryForm.username || undefined,
      operationType: queryForm.operationType || undefined,
      module: queryForm.module || undefined,
      startTime: queryForm.timeRange?.[0] || undefined,
      endTime: queryForm.timeRange?.[1] || undefined,
      logType: 2 // 操作日志类型
    }
    
    // 调用后端API获取系统日志列表
    const response = await getSystemLogList(params)
    
    if (response.data) {
      // 转换为操作日志格式
      logList.value = response.data.records.map((log: SystemLog) => ({
        id: log.id,
        username: log.username,
        operationType: log.operationName || '',
        module: log.moduleName || '',
        description: log.operationDesc || '',
        ipAddress: log.ipAddress || '',
        userAgent: log.userAgent || '',
        status: log.status || 1,
        operationTime: log.logTime || log.createTime || '',
        requestParams: log.requestParams || '',
        responseResult: log.responseResult || '',
        errorMessage: log.errorMessage || ''
      }))
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取操作日志失败:', error)
    showMessage({ type: 'error', message: '获取操作日志失败' })
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  getOperationLogList()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    username: '',
    operationType: '',
    module: '',
    timeRange: []
  })
  pagination.current = 1
  getOperationLogList()
}

// 导出日志
const handleExport = async () => {
  try {
    exporting.value = true
    // TODO: 调用后端API导出操作日志
    // await operationLogApi.exportOperationLog(queryForm)
    showMessage({ type: 'success', message: '导出成功' })
  } catch (error) {
    console.error('导出失败:', error)
    showMessage({ type: 'error', message: '导出失败' })
  } finally {
    exporting.value = false
  }
}

// 清空日志
const handleClear = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有操作日志吗？此操作不可恢复！', '确认清空', {
      type: 'warning'
    })
    
    clearing.value = true
    // TODO: 调用后端API清空操作日志
    // await operationLogApi.clearOperationLog()
    showMessage({ type: 'success', message: '清空成功' })
    getOperationLogList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空失败:', error)
      showMessage({ type: 'error', message: '清空失败' })
    }
  } finally {
    clearing.value = false
  }
}

// 查看详情
const handleViewDetail = (row: OperationLog) => {
  currentLog.value = row
  detailVisible.value = true
}

// 关闭详情
const handleCloseDetail = () => {
  detailVisible.value = false
  currentLog.value = {} as OperationLog
}

// 选择变化
const handleSelectionChange = (selection: OperationLog[]) => {
  selectedLogs.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  getOperationLogList()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  getOperationLogList()
}

// 获取操作类型标签类型
const getOperationTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'LOGIN': 'success',
    'LOGOUT': 'info',
    'CREATE': 'primary',
    'UPDATE': 'warning',
    'DELETE': 'danger',
    'QUERY': 'info',
    'EXPORT': 'success',
    'IMPORT': 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取操作类型文本
const getOperationTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'LOGIN': '登录',
    'LOGOUT': '登出',
    'CREATE': '新增',
    'UPDATE': '修改',
    'DELETE': '删除',
    'QUERY': '查询',
    'EXPORT': '导出',
    'IMPORT': '导入'
  }
  return typeMap[type] || type
}

// 获取模块文本
const getModuleText = (module: string) => {
  const moduleMap: Record<string, string> = {
    'USER': '用户管理',
    'ROLE': '角色管理',
    'PERMISSION': '权限管理',
    'REGION': '区域管理',
    'PROPERTY': '物业管理',
    'PARKING': '停车管理',
    'SECURITY': '安防管理',
    'SYSTEM': '系统配置'
  }
  return moduleMap[module] || module
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dateTime
}

// 格式化JSON
const formatJson = (json: string) => {
  try {
    return JSON.stringify(JSON.parse(json), null, 2)
  } catch {
    return json
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getOperationLogList()
})
</script>

<style scoped>
.operation-log-container {
  padding: 20px;
}

.log-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.log-detail-pre {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 200px;
  overflow-y: auto;
}

.error-message {
  color: #f56c6c;
  background-color: #fef0f0;
}
</style> 